var g_priceScale = 2;
g_product = 'hr';

/////////////////////////// tab bar ///////////////////////////////////////////
function getNearForm(btn) {
	return $(btn).closest('.jform');
}
function getPopupTabTarget(btn) {
	var v = btn.getAttribute('value');
	if (v == null) {
		v = $(btn).html();
	}
	return '_popupTab_' + getModelName(getNearForm(btn)) + ':' + v;
}
function addRecord(btn, url) {
	submitPage(btn, buildRequest(btn, 'add',url));
}
function _addRecord(btn, url) {
	openLink(buildRequest(btn, '_add',url), getPopupTabTarget(btn), getText('commons.add'), btn);
}

function _copyRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_copy', true);
}

function _updateRecordInBlank($tr, url, id) {
	openBlank($tr, url + id + '&_layout=whole');
}
function _acceptRecord($tr, url, id) {
	var title = getModelName($tr.closest('.jform')) + ':' + getText('commons.accept');
	openMainTab(url + id, title, null, $tr);
}

function _importLayoutRecord(btn) {
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	var url = g_base_site + '/espirit/eap/pagelayout/pageUpgrade._importLayout.html';
	openMainTab(url, title, null, btn);
}
function exportLayoutRecord(btn) {
	openBlank(btn, g_base_site + '/espirit/eap/pagelayout/pageUpgrade.exportLayout.html?', true);
}
function exportLayoutWithDataRecord(btn) {
	openBlank(btn, g_base_site + '/espirit/eap/pagelayout/pageUpgrade.exportLayoutWithData.html?', true);
}

function printRecord(btn, url) {
	/*if (!url) {		
		var $form = $(btn).closest('.jform');
		url = $form.attr('action');
	}
	var extraParams = 'path=' + url;
	var printUrl = buildRequest(btn, 'print', url, extraParams);
	openBlank(btn, printUrl);*/
	webprint(btn, url);
}
function webprint(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	
	if (!url) {		
		var $form = $(btn).closest('.jform');
		url = $form.attr('action');
	}
	
	var idObjs = $("[name$='.id']", getActiveDom());
	var params = "";
	idObjs.each(function() {
		var idObj = this;
		if (idObj.checked) {
			params = params + '&model.id=' + idObj.value;
			return true;
		}
	});
	var printUrl = buildRequest(btn, 'print', url);
	if (printUrl.indexOf('?') == -1) {
		printUrl += '?_resultCode=$print' + params;
	} else {		
		printUrl += '&_resultCode=$print' + params;
	}
	window.open(printUrl, 'print', 'status=no,menubar=yes,location=no');
}
function showPrintPreview() {
	//window.print();
}

function _searchRecord(btn, url) {
	var name = btn.getAttribute('name');
	if (name == 'execute._smartSearch') {
		_smartSearch(btn, url);
	} else if (name == 'execute._searchWeb') {
		_searchWeb(btn, url);
	} else {
		var title = btn.getAttribute('value');
		if (title == null) {
			title = $(btn).html();
		}
		if (!title) {
			title = getText('commons.search');
		}
		openLink(buildRequest(btn, '_search',url), getPopupTabTarget(btn), title, btn);
	}
}

function submitSelectedPageinfo(btn, url, targetMethod, selectOneAtLeast) {
	var params = getSelectedPageinfoIds(btn);
	if (selectOneAtLeast && Object.keys(params).length == 0) {
		infoPleaseSelectRecord();
		return;
	}
	
	var hasSeparator = url && (url.indexOf('?') >= 0);
	url = buildRequest(btn, targetMethod, url) + (hasSeparator?'':'?') + toParameters(params);
	var title = getModelName(getNearForm(btn)) + ':' + $(btn).html();
	openMainTab(url, title, null, btn);
}

function _reCalcTicketRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_reCalcTicket', false);
}
function _reCalcSalaryRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_reCalcSalary', false);
}
function _pay(btn, url) {
	submitSelectedPageinfo(btn, url, '_pay', true);
}
function _generateBankCollectionRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateBankCollection', false);
}
function _generateSchedualRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_generateSchedual', false);
}
function _quoteRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_quote', true);
}

function _mergeRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_merge', true);
}

function changePassword(btnObj) {
	var $form = $(btnObj).closest('.jform');
	var password1 = $('[name=password]', $form).val();
	var password2 = $('[name=password2]', $form).val();

	if (password1 != password2) {
		showError(g_text['errors.passwordNotMatched']);
	} else {
		ajaxSubmit($form, {
			success: function(data) {
				var $data = $(data);
				if ($data.hasClass('error')) {
					showError($data.html());
				} else {
					showSuccess(g_text['user.changePassword.success']);
				}
			}
		});
	}
}

function _addFromCarRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_addFromCar', false);
}

function _approveRecord(btn, url) {
		var selectedIds = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(selectedIds).length;
	if (selectedCount == 0){
		infoPleaseSelectRecord();
		return;
	}
	//should select only one record
	if (selectedCount > 1){
		info(g_text['commons.onlyOneRecordPermit']);
		return;
	}
	
	var url = buildRequest(btn, '_approve', url) + '?' + toParameters(selectedIds);
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	openMainTab(url, title, null, btn);
}


function _changeRecord(btn, url) {
	submitSelectedPageinfo(btn, url, '_change', true);
}

function addFromCarRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	
	// Special Logic for salesOrderItem
	var $form = $(btn).closest('.jform');
	var action = $form.attr('action');
	var isSalesOrderItem = action.indexOf('salesOrderItem') > 0;
	if (isSalesOrderItem) {
		var params = serialize($form);
		var sParams = '';
		for (var key in params) {
			var newKey = key.replace('results','carItems');
			sParams += '&' + newKey + '=' + params[key];
		}
		sParams = sParams.replace('results','carItems');
		openLink(g_base_site + '/espirit/sale/salesOrderItem._generatePL.html?' + sParams, g_text['model.espirit.sale.packingList'], g_text['model.espirit.sale.packingList']);
	} else {		
		submitPage(btn, url);
	}
}
function removeRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'remove',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
//	submitPage(btn, url, '_hidden');
//	submitPage(btn, buildRequest(btn, 'remove',url), '_hidden');
}

function addToCarRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var url = buildRequest(btn, "addToCar",url) + '?_resultCode=$noResult';
	var $form = $(btn).closest('.jform');
	var data = serialize($form);
	$.post(url, data);
	
	//mock message impletention
	showSuccess(g_text['commons.addToCarSucess']);
}
// add web search item to shopping cart
function addToCar(linkObj, id) {
	if ($(linkObj).hasClass('itemExisted')) {
		var url = g_base_site + '/espirit/common/netSearch.remove.html?_resultCode=$noResult&results[0].id=' + id;
		$.get(url, function() {
			$(linkObj).removeClass('itemExisted');
			showSuccess(g_text['commons.removeFromCarSucess']);
		});
	} else {
		var url = g_base_site + '/espirit/common/netSearch.addToCar.html?_resultCode=$noResult&results[0].id=' + id;
		$.get(url, function() {
			$(linkObj).addClass('itemExisted');
			showSuccess(g_text['commons.addToCarSucess']);
		});
	}
}
function addToMatch(linkObj, id) {
	var rfqItemId = $(linkObj).closest('.netSearchCtn').attr('rfqItemId');
	
	var url = g_base_site + '/espirit/common/netSearch.addToMatch.html?_resultCode=$noResult&rfqItem.id=' + rfqItemId + '&model.id=' + id;
	$.get(url, function() {
		$(linkObj).addClass('itemExisted');
		showSuccess(g_text['commons.addToMatchSucess']);
	});
}
function infoPleaseSelectRecord(){
	info(g_text['commons.pleaseSelectRecord']);
}
function info(info){
	showError(info, 300);
}

function existsSelectedItem(btn){
	var $form = getNearForm(btn);
	var $pageinfo = $form.find('.jpageinfolist:first');
	var $tr = $('table:last tbody>tr:not(.childContainer)', $pageinfo);
	return $tr.find('input:checked[value]').length > 0;
}

function needToCallRecord(btn, url) {
	submitPage(btn, url, '_hidden');
}
function setCompletedFlagRecord(btn, url) {
	submitPage(btn, url, '_hidden');
}



function removeMatchedItemRecord(btn, url) {
	submitPage(btn, url, '_hidden');
}

function closeRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}

	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'close',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
}


function confirmRecord(btn,url,act) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var deleteRequest = "" + buildRequest(btn, act);
	$.confirm({
		'title'		: getText('commons.' + act),
		'message'	: getText('commons.' + act + 'Confirm'),
		'buttons'	: {
			'确认' : {
				'class'	: 'blue',
				'action': function() {
					var idObjs = $("[name$='.id']", getActiveDom());
					var params = "";
					idObjs.each(function() {
						var idObj = this;
						if (idObj.checked) {
							params = params + '&' + idObj.name + '=' + idObj.value;
						}
					});
					
					if (deleteRequest.indexOf('?') > 0) {
						deleteRequest = deleteRequest + params;
					} else {
						deleteRequest = deleteRequest + '?' + params;
					}
					openLink(deleteRequest,null,null,btn);
				}
			},
			'取消' : {
				'class'	: 'gray',
				'action': function(){}
			}
		}
	});
}

function backAcceptRecord(btn, url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}

	var $form = $(btn).closest('.jform');
	var newUrl = buildRequest(btn, 'backAccept',url);
	$.ajax({
		url: newUrl,
		data: serialize($form),
		success:function(data) {
			var $data = $(data);
			if ($data.hasClass('error')) {
				showError($data.html());
			} else {
				refreshCurrentTab();
			}
		}
	});
}


function reportRecord(btn, url) {
	var params = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(params).length;
	if (selectedCount == 0){
		infoPleaseSelectRecord();
		return;
	}

	params._resultCode = '$noResult';
	var hasSeparator = (url.indexOf('?') >= 0);
	url = buildRequest(btn, 'report', url) + (hasSeparator?'':'?') + toParameters(params);
	openBlank(btn, url);
}

function _goNextRecord(btn, url) {
	var selectedIds = getSelectedPageinfoIds(btn);
	var selectedCount = Object.keys(selectedIds).length;
	if (selectedCount == 0){
		infoPleaseSelectRecord();
		return;
	}
	//should select only one record
	if (selectedCount > 1){
		info(g_text['commons.onlyOneRecordPermit']);
		return;
	}
	
	var url = buildRequest(btn, '_goNext', url) + '?' + toParameters(selectedIds);
	var $btn = $(btn);
	var $form = $btn.closest('.jform');
	var title = getModelName($form) + ':' + $btn.html();
	openMainTab(url, title, null, btn);
}


function _batchAddRecord(btn, url) {
//	submitPage(btn, buildRequest(btn, '_batchAdd',url), getPopupTabTarget(btn),true);
	openLink(buildRequest(btn, '_batchAdd',url), getPopupTabTarget(btn), getText('action._batchAdd'), btn);
}

function _importFileRecord(btn, url) {
	openLink(buildRequest(btn, '_importFile',url), getPopupTabTarget(btn), getText('action._importFile'), btn);
}
function statRecord(btn) {
	var $form = $(btn).closest('.jform');
	var $target = $form.next('.statRecord');
	if ($target.length == 0) {
		$form.after('<div class="statRecord" style="clear:both"></div>');
		$target = $form.next('.statRecord');
	}
	var $tab = $form.find('.jtab').eq(0);
	var selectIndex = $tab.tabs("option", "selected");
	var options = {
		includeBlankValue: true,
		data: {
			"newSearch": true,
			"model.customerPartItemSales": selectIndex
		},
		beforeSend: function() {
			addLoading($target);
		},
		success:function(data) {
			removeLoading($target);
			$target.html(data);
		}
	};
	ajaxSubmit($form, options);
}


function formatPrice(num, dec) {
	if (!dec) {
		dec = g_priceScale;
	}
	var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
	return result;
}

function backRecord(btn,url) {
	if (!existsSelectedItem(btn)){
		infoPleaseSelectRecord();
		return;
	}
	var deleteRequest = "" + buildRequest(btn, 'back');
	$.confirm({
		'title'		: getText('commons.back'),
		'message'	: getText('commons.backConfirm'),
		'buttons'	: {
			'确认' : {
				'class'	: 'blue',
				'action': function() {
					var idObjs = $("[name$='.id']", getActiveDom());
					var params = "";
					idObjs.each(function() {
						var idObj = this;
						if (idObj.checked) {
							params = params + '&' + idObj.name + '=' + idObj.value;
						}
					});
					
					if (deleteRequest.indexOf('?') > 0) {
						deleteRequest = deleteRequest + params;
					} else {
						deleteRequest = deleteRequest + '?' + params;
					}
					openLink(deleteRequest,null,null,btn);
				}
			},
			'取消' : {
				'class'	: 'gray',
				'action': function(){}
			}
		}
	});
}

function submitLog(btn) {
	if ($(btn).hasClass("disabled")) {
		return;
	}
	
	var $input = $(btn).closest('.sysLogInput').find('input:first');
	if ($input.val() !='') {
		var $form = $(btn).closest('.jform');
		// lock the button 10 seconds to avoid duplicated click
		$(btn).addClass("disabled"); 
		setTimeout(function() {
			$(btn).removeClass("disabled");
		}, 10000);
		
		ajaxSubmit($form, {
			success:function(data) {
				$(btn).removeClass("disabled");
				var $data = $(data);
				if ($data.hasClass('error')) {
					showError($data.html());
				} else {
					$form.parent().html(data);
				}
				$data.find('.sysLogInput input:first').focus();
			}
		});
	}
}

// im.notice.ftl
function openNotice(link, countId, target, text) {
	var count = Number($('#' + countId).html());
	if (count > 0) {
		var cleanLink = g_base_site + '/espirit/common/userNotice.cleanNotice.html?_resultCode=$json&type=' + countId.substring(0, countId.length - 6);
		$.get(cleanLink);
	}
	openMainTab(link, text);
	
	$('#noticeMenu').hide();
	$('#' + countId).html('0');
	var totalCount = Number($('#countNotice').html());
	var newTotalCount = totalCount - count;
	$('#countNotice').html(newTotalCount);
	if (newTotalCount == 0) {
		$('#noticeTip').hide();
	}
}

function updateNotice(notice) {
	if (!notice) {
		return;
	}
	
	// FIMXE: change notice header to RED
	var total = 0;
	total += updateNoticeToLabel('rfqNotice', notice.rfq);
	total += updateNoticeToLabel('purchaseNotice', notice.purchase);
	total += updateNoticeToLabel('approvingSINotice', notice.approvingSI);
	total += updateNoticeToLabel('approvingPINotice', notice.approvingPI);
	total += updateNoticeToLabel('approvingPLINotice', notice.approvingPLI);
	total += updateNoticeToLabel('receiveNotice', notice.receive);
	total += updateNoticeToLabel('siReceiveNotice', notice.siReceive);
	total += updateNoticeToLabel('shipNotice', notice.ship);
	total += updateNoticeToLabel('needToBuyItemNotice', notice.needToBuyItem);
	total += updateNoticeToLabel('messageNotice', notice.message);
	total += updateNoticeToLabel('rfqItemAllocateNotice', notice.rfqItemAllocate);
	if (total == 0) {
		$('#noticeTip').hide();
	} else {
		$('#noticeTip').show();
		$('#countNotice').html(total);
	}
}
function updateNoticeToLabel(id, val) {
	if (!val) {
		val = 0;
	}
	var $label = $('#' + id);
	if ($label.length > 0) {
		$label.html(val);
		return val;
	} else {
		return 0;
	}
}
function loadAndUpdateNotice() {
	$.ajax({
		url: g_base_site + '/espirit/common/userNotice.view.html?_resultCode=$json&properties=id,rfq,purchase,message,receive,ship,siReceive,approvingSI,approvingPI,approvingPLI,needToBuyItem,rfqItemAllocate',
		success: function(data) {
			try {
				var jsonData = $.parseJSON(data);
				updateNotice(jsonData);
			} catch(ex) {
				$('#noticeArea').html(data);
			}
		}
	});
}

//im.notice.ftl - end